<template>
  <div class="root-table-bar">
    <!-- ================================================================= -->
    <vxe-toolbar
      id="list-management"
      export
      :refresh="{ query: findList }"
      :custom="{ storage: true }"
    >
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="handleClick('', 'add','')">新增</el-button>
        <el-button @click="handleClick('', 'start','')">启用</el-button>
        <el-button @click="handleClick('', 'block','')">停用</el-button>

      </template>
    </vxe-toolbar>
    <!-- ================================================================= -->

    <vxe-table
      ref="xTable"
      border
      stripe
      height="600"
      highlight-current-row
      highlight-hover-row
      show-header-overflow
      show-overflow
      :sort-config="tableProps.sortConfig"
      @sort-change="sortChange"
      :columnMinWidth="tableProps.columnWidth"
      :align="tableProps.allAlign"
      :data="tableData"
      :loading="loading"
      class="custom-scrollbar"
      auto-resize
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <!-- ================================================================= -->
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="status" title="状态" min-width="100" sortable show-header-overflow show-overflow :formatter="formatterStatus"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.status" placeholder="请选择状态" clearable>
            <el-option value="0" label="启用"/>
            <el-option value="1" label="停用"/>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="contractNo" title="合同号" min-width="200" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.contractNo" placeholder="请输入合同号" clearable />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="warehouseName" title="所属仓库" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseCode" placeholder="请输入所属仓库 " style="width:100%" clearable>
            <el-option
              v-for="item in warehouseData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="shipmentName" title="入驻商" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.shipmentName" placeholder="请输入入驻商" clearable />
        </template>
      </vxe-table-column>
      <!-- ================================================================= -->

      <vxe-table-column>
        <vxe-table-column
          field="gmtEffective"
          title="生效日期"
          sortable
          :min-width="tableProps.dateWidth"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtEffective"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width: 100%"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtEffective')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtIneffective"
          title="失效日期"
          sortable
          :min-width="tableProps.dateWidth"
        />
        <template v-slot:header>
          <el-date-picker
            type="daterange"
            value-format="yyyy-MM-dd"
            v-model="gmtIneffective"
            :picker-options="pickerOptions"
            style="width: 100%"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtIneffective')"
          />
        </template>
      </vxe-table-column>

      <!-- ================================================================= -->
      <vxe-table-column>
        <vxe-table-column field="createdName" title="创建人" sortable />
        <template v-slot:header>
          <el-input
            placeholder="请输入"
            v-model="listQuery.createdByName"
          ></el-input>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          title="创建时间"
          sortable
          :min-width="tableProps.dateWidth"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtCreated"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width: 100%"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDates(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="modifiedName" title="修改人" sortable />
        <template v-slot:header>
          <el-input
            placeholder="请输入"
            v-model="listQuery.modifiedByName"
          ></el-input>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtModified"
          title="修改时间"
          sortable
          :min-width="tableProps.dateWidth"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtModified"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width: 100%"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDates(value, 'gmtModified')"
          />
        </template>
      </vxe-table-column>
      <!-- ==============================操作区域============================ -->
      <vxe-table-column title="操作" fixed="right">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="详情" placement="top">
            <vxe-button type="text" @click="handleClick(scope.row.code, '','')">
              <i class="el-icon-document" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="编辑"
            placement="top"
          >
            <vxe-button
              type="text"
              @click="handleClick(scope.row.code, 'edit',scope.row.status)"
            >
              <i class="el-icon-edit" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="删除"
            placement="top"
          >
            <vxe-button
              type="text"
              @click="handleClick(scope.row.code, 'dispose',scope.row.status)"
            >
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />
  </div>
</template>
<script>
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  import VXEUtils from 'vxe-utils'
  import myMixin from './myMixin'
  // import { purchaseList,saleList,contractDelete,saleAnnul } from "./api";
  import { contractActive, contractDelete, contractList, contractUnActive, getWarehouse } from '@/api/basicInfo'

  Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ["cookie"] });
  // import myInput from "./myInput";

  export default {
  props: ["index"],
  mixins: [myMixin],
  data: () => ({
    loading: false,
    tableProps: {
      allAlign: "center",
      columnWidth: "150px",
      dateWidth: "400px",
      inputWidth: "180px",
      sortConfig: {
        remote: true,
      },
    },
    warehouseData: [],
    gmtEffective:'',
    gmtIneffective:"",
    listQuery: {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      sortField: "",
      sortType: "",
      status: "",
      shipmentName:'',
      warehouseCode: "",
      createdByName:'',
      contractNo:'',
      code: "",
      modifiedByName:'',
      sourceCode: "",
      shipmentCode: "",
      purchaseType: "",
      planQuantityFloor: "",
      planQuantityCeiling: "",
      actualQuantityFloor: "",
      actualQuantityCeiling: "",
    },
    tableData: [],
  }),
  created(){
    this.getWarehouse()

    this.findList();

  },

  mounted() {
    this.$eventBus.$on("refreshList", () => {
      this.findList()
    })
  },
  methods: {
      //仓库查询
      getWarehouse() {
        getWarehouse().then(response => {
          this.warehouseData = response.data
        })
      },

    // 新增 启用 停用 详情 修改 作废
    handleClick() {
      switch (arguments[1]) {
        case "edit":
          if(this.index == 'purchase'){
            this.$router.push({
              path: "/basicInfo/contractEdit",
              query: {
                code: arguments[0],
              },
            });
          }
          break;
        case "dispose":
          // 作废
          this.$confirm('确认作废吗？').then(_ => {
            if(this.index == 'purchase'){
              console.log(arguments)
              contractDelete(arguments[0]).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.findList()
              }).catch(() => this.loading = false)
            }
          })
          break;
        case "add":
          // 新增
          if(this.index == 'purchase'){
            this.$router.push({
              path: "/basicInfo/contractAdd"
            });
          }
          break;
        case "start":
          // 启用
          if(this.index == 'purchase'){
            let selectRecords = this.$refs.xTable.getCheckboxRecords()
            let arr = []
            selectRecords.forEach( i => {
              arr.push(i.code)
            })
            arr = arr.join(",");
            if (arr.length != 0) {
              this.$confirm('确认启用吗？').then(_ => {
                this.loading = true
                contractActive(arr).then(response => {
                  this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
                  this.findList()
                  this.loading = false
                }).catch(() => this.loading = false)
              })
            }else{
              this.$message('没有能启用的数据！')
            }
          }
          break;
        case "block":
          // 停用
          if(this.index == 'purchase'){
            let selectRecords = this.$refs.xTable.getCheckboxRecords()
            let arr = []
            selectRecords.forEach( i => {
              arr.push(i.code)
            })
            arr = arr.join(",");
            if (arr.length != 0) {
              this.$confirm('确认停用吗？').then(_ => {
                this.loading = true
               contractUnActive(arr).then(response => {
                    this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
                  this.findList()
                  this.loading = false
                }).catch(() => this.loading = false)
              }).catch(_ => {
              })
            }else{
              this.$message('没有能停用的数据！')
            }
          }
          break;

        default:
          if(this.index == 'purchase'){
            this.$router.push({
              path: "/basicInfo/contractDetail",
              query: {
                code: arguments[0],
              },
            });
          }

          break;
      }
    },
    // 翻译状态
    formatterStatus({ cellValue }) {
      if (cellValue === '0') {
        return '启用'
      } else if (cellValue === '1') {
        return '停用'
      }
    },

    //排序
    sortChange({ column, property, order }) {
      if (this.tableData.length && order) {
        this.listQuery.sortField = property;
        this.listQuery.sortType = order;
        this.findList();
      }
    },
    // 分页
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage;
      this.listQuery.pageSize = pageSize;
      this.findList();
    },
    // 获取采购单
    findList() {
      this.loading = true;
       return  contractList(this.listQuery).then((response) => {
        this.tableData = response.data.records;
        this.listQuery.total = response.data.total;
        this.loading = false;
      }).catch(() => this.loading = false)
    },
    // 动态 添加日期区间后缀
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Begin`] = value[0];
        this.listQuery[`${prefix}End`] = value[1];
      } else {
        this.listQuery[`${prefix}Begin`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    changeDates(value, prefix) {
        if (value) {
            this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
            this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
        } else {
            this.listQuery[`${prefix}Start`] = "";
            this.listQuery[`${prefix}End`] = "";
        }
    },
  },
  destroyed() {
    this.$eventBus.$off('refreshList')
  },
};
</script>
<style lang="scss" scoped>
</style>
